package com.gewu.teday.fragmnet

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gewu.teday.R
import com.gewu.teday.adapter.IdeaListAdapter
import com.gewu.teday.adapter.IedaListBean
import com.gewu.teday.adapter.LegendBean
import com.gewu.teday.adapter.LineChartLegendAdapet
import com.gewu.teday.bean.DataBeans
import com.gewu.teday.bean.ItemIedaBenans
import com.gewu.teday.utils.GwDialog
import com.gewu.teday.utils.SpUtils
import com.gewu.teday.utils.Util
import com.github.mikephil.charting.charts.CombinedChart
import com.github.mikephil.charting.components.*
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.ValueFormatter
import kotlinx.android.synthetic.main.idea_fragment.*
import kotlinx.android.synthetic.main.idea_fragment.view.*
import kotlinx.android.synthetic.main.idea_fragment.view.listview
import kotlinx.android.synthetic.main.idea_fragment.view.spinner
import kotlinx.android.synthetic.main.more_layout.view.*
import kotlinx.android.synthetic.main.zhengti_fragmnet.view.*
import java.util.*
import kotlin.collections.ArrayList


open class TeDayFragment : BaseFragment(), IdeaListAdapter.Onclick {

    private var viewList = ArrayList<View>()
    private var viewList1 = ArrayList<View>()
    private var listAda = ArrayList<ItemIedaBenans>()
    private val starArray = arrayOf("近 7 天", "近30天", "近三月")
    private var mCombinedChart: CombinedChart? = null

    override fun getLayoutId(): Int = R.layout.idea_fragment

    override fun initView() {
        if (viewList.isNotEmpty()) {
            viewList.clear()
        }

        if (viewList1.isNotEmpty()) {
            viewList1.clear()
        }

        view?.post {
            viewList.add(requireView().all)
            viewList.add(requireView().wenzhang)
            viewList.add(requireView().weitoutiao)
            viewList.add(requireView().wenda)
            viewList.add(requireView().shipin)
            viewList1.add(requireView().all1)
            viewList1.add(requireView().wenzhang1)
            viewList1.add(requireView().weitoutiao1)
            viewList1.add(requireView().wenda1)
            viewList1.add(requireView().shipin1)
            select(requireView().all)
            select1(requireView().all1)
        }

        view?.let {
            setOnclick(it)
        }

        setListView()

        view?.let {
            addTextCount(it)
        }
    }

    val list = ArrayList<ItemIedaBenans>()

    private fun addTextCount(it: View) {
        it.addtext?.setOnLongClickListener(object : View.OnLongClickListener {
            override fun onLongClick(p0: View?): Boolean {
                val build = context?.let { GwDialog(it).LayoutBuilder() }
                val create =
                    build?.create(R.layout.teday_window, false, Gravity.CENTER, R.drawable.shape)
                create?.show()
                val viewlayout = build?.getView()

                val cancel = viewlayout?.findViewById<ImageView>(R.id.cancel)
                val zuopinbiaoti = viewlayout?.findViewById<EditText>(R.id.zuopinbiaoti)
                val chuangzuoshouyi = viewlayout?.findViewById<EditText>(R.id.chuangzuoshouyi)
                val jichushouyi = viewlayout?.findViewById<EditText>(R.id.jichushouyi)
                val sucess = viewlayout?.findViewById<TextView>(R.id.sucess)
                viewlayout?.findViewById<LinearLayout>(R.id.bankNum)!!.visibility = View.GONE
                viewlayout.findViewById<LinearLayout>(R.id.bankTime)!!.visibility = View.GONE
                viewlayout.findViewById<TextView>(R.id.teday_tip)!!.visibility = View.GONE
                cancel?.setOnClickListener {
                    create?.dismiss()
                }

                sucess?.setOnClickListener {
                    if (zuopinbiaoti?.text.isNullOrEmpty() || chuangzuoshouyi?.text.isNullOrEmpty() || jichushouyi?.text.isNullOrEmpty()) {
                        Toast.makeText(context, "不能为空", Toast.LENGTH_SHORT).show()
                    } else if (chuangzuoshouyi?.text!!.length > 6 || jichushouyi?.text!!.length > 6) {
                        Toast.makeText(context, "长度超过限制", Toast.LENGTH_SHORT).show()
                    } else {
                        val itemIedaBenans = ItemIedaBenans(
                            zuopinbiaoti?.text.toString(),
                            chuangzuoshouyi.text.toString(),
                            jichushouyi.text.toString()
                        )
                        moenyListAdapter?.addList(itemIedaBenans)
                        moenyListAdapter?.notifyDataSetChanged()

                        val decodeString: IedaListBean? = SpUtils.instances?.decodeParcelable(
                            "textlist",
                            IedaListBean::class.java
                        )
                        if (decodeString != null) {
                            val listitem = decodeString.list
                            listitem.add(itemIedaBenans)
                            SpUtils.instances?.encodeParcelable("textlist", decodeString)
                        } else {
                            list.add(itemIedaBenans)
                            val iedaListBean = IedaListBean(list)
                            SpUtils.instances?.encodeParcelable("textlist", iedaListBean)
                        }
                        create?.dismiss()
                    }
                }
                return true
            }
        })
    }

    private var decode: DataBeans? = null

    override fun initData() {
        decode = SpUtils.instances?.decodeParcelable("data", DataBeans::class.java)
        decode?.let { data(it) }
        initLegend()
        setAdapter()
    }

    private fun setAdapter() {
        val decodeString: IedaListBean? =
            SpUtils.instances?.decodeParcelable("textlist", IedaListBean::class.java)
        if (decodeString != null) {
            for (i in 0 until decodeString.list.size) {
                moenyListAdapter?.addList(decodeString.list[i])
            }
            moenyListAdapter?.notifyDataSetChanged()
        }
    }

    /**
     * 得到折线图(一条)
     * @param lineChartY 折线Y轴值
     */
    private fun getLineData(lineChartY: List<String>): LineData {
        val yValues: ArrayList<Entry> = ArrayList()
        val xValue: ArrayList<Float> = ArrayList()
        for (i in 0 until 7) {
            xValue.add(lineChartY[i].toFloat())
        }

        val reversed = xValue.reversed()
        for (i in 0 until 7) {
            yValues.add(Entry(i.toFloat(), reversed[i]))
        }
        val lineData = LineData()
        val dataSet = LineDataSet(yValues, "")
        dataSet.lineWidth = 1f
        dataSet.isHighlightEnabled = false
        dataSet.mode = LineDataSet.Mode.LINEAR
        dataSet.color = Color.parseColor("#E99563")
        //显示值
        dataSet.setDrawValues(false)
        dataSet.setDrawCircles(false)
        dataSet.setDrawCircleHole(false)
        dataSet.formSize = 15F
        dataSet.axisDependency = YAxis.AxisDependency.LEFT
        lineData.addDataSet(dataSet)
        return lineData
    }


    /**
     * 得到柱状图
     * @param barChartY Y轴值
     * @param barName   柱状图名字
     */
    private fun getBarData(barChartY: List<String>): BarData {
        val yValues: ArrayList<BarEntry> = ArrayList()
        val xValue: ArrayList<Float> = ArrayList()
        for (i in 0 until 7) {
            xValue.add(barChartY[i].toFloat())
        }

        val reversed = xValue.reversed()
        for (i in 0 until 7) {
            yValues.add(BarEntry(i.toFloat(), reversed[i]))
        }

        val barData = BarData()
        barData.barWidth = 0.3F
        mCombinedChart?.xAxis?.axisMaximum = (xValue.size - 0.5).toFloat()
        val barDataSet = BarDataSet(yValues, "")
        barDataSet.color = Color.parseColor("#90C228")
        barDataSet.setDrawValues(false)
        barDataSet.isHighlightEnabled = false
        barData.addDataSet(barDataSet)
        return barData
    }

    private fun showCombinedChart(lisData: List<String>) {
        val combinedData = CombinedData()
        combinedData.setData(getBarData(lisData))
        combinedData.setData(getLineData(lisData))
        mCombinedChart?.data = combinedData
        //每次加载新数据自动滚动到最后 x轴从右往左滑
        mCombinedChart?.moveViewToX(mCombinedChart!!.xChartMax)
        //动画平移(需平移到的X坐标值[将所设置值拉到X轴圆点]，需平移到的Y坐标值[将所设置值拉到Y轴中心]，需平移的坐标轴，动画时长)
        mCombinedChart?.xChartMax?.let {
            mCombinedChart!!.moveViewToAnimated(
                it,
                0f,
                YAxis.AxisDependency.LEFT,
                1000
            )
        }
        mCombinedChart?.invalidate()
    }

    fun data(dataBeans: DataBeans) {
        hander?.postDelayed({
            topText(dataBeans)
            initSpinner(dataBeans)
            initLinchart(dataBeans)
            showCombinedChart(dataBeans.moneylist)
        }, 500)
    }

    private fun topText(dataBeans: DataBeans) {
        if (Util.afterTimeCalendar()) {
            val s =
                if (dataBeans.moneylist.isNotEmpty() || dataBeans.mothlist.isNotEmpty()) dataBeans.moneylist[0].toString() else "0"
            view?.leiji_moneys?.text = if (dataBeans.leijiNum.isEmpty()) "0" else dataBeans.leijiNum
            view?.teday_money?.text = s
            view?.jichu_money?.text = s
        } else {
            view?.leiji_moneys?.text = if (dataBeans.leijiNum.isEmpty()) "0" else dataBeans.leijiNum
            view?.teday_money?.text = "待更新"
            view?.jichu_money?.text = "待更新"
        }
    }

    private fun initSpinner(dataBeans: DataBeans) {
        requireView().spinner.adapter =
            context?.let { ArrayAdapter(it, android.R.layout.simple_list_item_1, starArray) }
        requireView().spinner.setSelection(dataBeans.type)
    }

    private fun initLegend() {
        val listLegend = ArrayList<LegendBean>()
        listLegend.add(LegendBean("#E99563", "创作收益"))
        listLegend.add(LegendBean("#5385FB", "文章收益"))
        listLegend.add(LegendBean("#5AC3C2", "视频收益"))
        listLegend.add(LegendBean("#9DCB4C", "微头条收益"))
        listLegend.add(LegendBean("#F3D847", "问答收益"))
        requireView().gridview.layoutManager =
            StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL)
        requireView().gridview.adapter =
            LineChartLegendAdapet(listLegend).apply { notifyDataSetChanged() }
    }

    private fun initLinchart(dataBeans: DataBeans) {
        mCombinedChart = view?.comchart
        val drawOrder = arrayOf(CombinedChart.DrawOrder.LINE, CombinedChart.DrawOrder.BAR)
        mCombinedChart?.drawOrder = drawOrder
        mCombinedChart?.setDrawGridBackground(false);
        mCombinedChart?.setDrawBarShadow(false);
        mCombinedChart?.isHighlightFullBarEnabled = false;
        mCombinedChart?.setDrawBorders(false);
        mCombinedChart?.setScaleEnabled(false);
        mCombinedChart?.isDragDecelerationEnabled = false;
        mCombinedChart?.isDragEnabled = false;
        mCombinedChart?.description?.isEnabled = false

        mCombinedChart?.legend?.isEnabled = false

        val leftAxis = mCombinedChart?.axisLeft;
        val rightAxis = mCombinedChart?.axisRight;
        val xAxis = mCombinedChart?.xAxis;

        //Y轴
        //是否绘制网格线
        rightAxis?.setDrawGridLines(false);
        rightAxis?.isEnabled = false;

        leftAxis?.setDrawAxisLine(false);//绘制X轴，默认为true
        leftAxis?.enableGridDashedLine(10f, 10f, 0f)
        leftAxis?.gridColor = resources.getColor(R.color.huise2)
        leftAxis?.textColor = resources.getColor(R.color.huise)
        leftAxis?.enableGridDashedLine(3F, 2F, 100F);
        leftAxis?.axisMinimum = 0F
        xAxis?.axisMinimum = -0.5f;
        xAxis?.setDrawGridLines(false);
        xAxis?.setDrawAxisLine(true);
        xAxis?.position = XAxis.XAxisPosition.BOTTOM;
        xAxis?.textColor = resources.getColor(R.color.huise)
        xAxis?.granularity = 1F
        xAxis?.valueFormatter = object : ValueFormatter() {
            override fun getAxisLabel(value: Float, axis: AxisBase?): String {
                return Util.formartTime(dataBeans.mothlist.reversed()[dataBeans.mothlist.size - 7 + value.toInt()])
            }
        }
    }

    private fun setOnclick(view: View) {
        view.all.setOnClickListener {
            select(view.all)
        }

        view.wenzhang.setOnClickListener {
            select(view.wenzhang)
        }

        view.weitoutiao.setOnClickListener {
            select(view.weitoutiao)
        }

        view.wenda.setOnClickListener {
            select(view.wenda)
        }

        view.shipin.setOnClickListener {
            select(view.shipin)
        }

        view.all1.setOnClickListener {
            select1(view.all1)
        }

        view.wenzhang1.setOnClickListener {
            select1(view.wenzhang1)
        }

        view.weitoutiao1.setOnClickListener {
            select1(view.weitoutiao1)
        }

        view.wenda1.setOnClickListener {
            select1(view.wenda1)
        }

        view.shipin1.setOnClickListener {
            select1(view.shipin1)
        }
    }

    private fun select(all: TextView) {
        for (i in 0 until viewList.size) {
            viewList[i].setBackgroundResource(R.drawable.textno_shape)
            val textView = viewList[i] as TextView
            textView.setTextColor(resources.getColor(R.color.black))
        }
        all.setBackgroundResource(R.drawable.textis_shape)
        all.setTextColor(resources.getColor(R.color.red))
    }

    private fun select1(all: TextView) {
        for (i in 0 until viewList1.size) {
            viewList1[i].setBackgroundResource(R.drawable.textno_shape)
            val textView = viewList1[i] as TextView
            textView.setTextColor(resources.getColor(R.color.black))
        }
        all.setBackgroundResource(R.drawable.textis_shape)
        all.setTextColor(resources.getColor(R.color.red))
    }

    private var moenyListAdapter: IdeaListAdapter? = null

    private fun setListView() {
        moenyListAdapter = IdeaListAdapter()
        moenyListAdapter!!.setOnClick(this)
        requireView().listview.adapter = moenyListAdapter
        requireView().listview.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    }

    @SuppressLint("NewApi", "NotifyDataSetChanged")
    override fun showDialog(index: Int) {
        val decodeString: IedaListBean? =
            SpUtils.instances?.decodeParcelable("textlist", IedaListBean::class.java)
        decodeString?.list?.removeAt(index)
        SpUtils.instances?.encodeParcelable("textlist", decodeString)
        moenyListAdapter?.notifyDataSetChanged()
    }

}